package com.qf.openapi.web.master.service.impl;

import cn.hutool.Hutool;
import cn.hutool.crypto.digest.DigestUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.openapi.web.master.dao.UserDao;
import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.ex.UserException;
import com.qf.openapi.web.master.service.UserService;
import com.qf.openapi.web.master.vo.ResultVo;
import com.qf.openapi.web.master.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    // 处理文件上传路径，使用依赖注入从propeties文件中获取配置
    @Value("${file.upload.path}")
    String fileUploadPath;


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public User getUser(Integer id) {
        return userDao.getUserById(id);
    }


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public User login(String username, String password) {

        //1. 根据用户名查询用户信息
        User user =  userDao.getUserByName(username);

        if (user == null){  // 没用匹配的用户，直接返回null
            return null;
        }else {
            //2. 比对密码是否正确
            final String dbpassword = user.getPassword();

            // 转换 password 为 md5 字符串
            final String md5password = DigestUtil.md5Hex(password);

            if (dbpassword.equals(md5password)){
                return user;
            }

            return null;
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void registUser(UserRegistVo userRegistVo) throws Exception {

        //0 检查当前用户名是否存在
        final String username = userRegistVo.getUsername();
        final User dbuser = userDao.getUserByName(username);
        if (dbuser!=null){
            // 用户名重复了
            throw new UserException(-1001,"用户名重复了");
        }


        //1. 保存文件到指定目录
        final MultipartFile photo = userRegistVo.getPhoto();

        // 生成一个唯一的文件名
        final String prefix = UUID.randomUUID().toString();
        final String fileName = prefix + "_" + photo.getOriginalFilename();

        final String finalFilePath = fileUploadPath + fileName;

        photo.transferTo(new File(finalFilePath));

        log.debug("上传头像成功,finalFilePath={}",finalFilePath);

        //2. 把用户的数据写入数据库表
        final User user = new User();

        user.setName(userRegistVo.getUsername());
        final String password = userRegistVo.getPassword();
        // password --->  md5
        final String md5Password = DigestUtil.md5Hex(password);
        user.setPassword(md5Password);

        user.setSex(userRegistVo.getSex());
        user.setBirthday(userRegistVo.getDate());

        user.setRegistTime(new Date());
        user.setPhotopath(fileName);

        userDao.insertUser(user);
        log.debug("用户数据落库成功,user={}",user);


    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ResultVo selectByLimit(User user,Integer page, Integer limit) {
        ResultVo ok = ResultVo.ok();
        PageHelper.startPage(page, limit);
        List<User> list = userDao.getAll(user);
        PageInfo<User> pageInfo = new PageInfo<>(list);
        final int count = (int) pageInfo.getTotal();
        ok.put("code",0);
        ok.put("message","ok");
        ok.put("count",count);
        ok.put("data",list);
        return ok;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo add(User user) {
        ResultVo resultVo = new ResultVo();
        User userByName = userDao.getUserByName(user.getName());
        if (userByName==null){
        }else {
            resultVo.put("message","用户已存在");
            return resultVo;
        }
        if (user.getPassword()==null){
            resultVo.put("message","密码不能为空");
        }
        user.setPassword(DigestUtil.md5Hex(user.getPassword()));
        if (user.getRegistTime()==null){
            user.setRegistTime(new Date());
        }
        userDao.insertUser(user);
        resultVo.put("message","ok");
        resultVo.put("data",user);
        return resultVo;
    }

    /**
     * 批量删除
     * @param list
     * @return
     */
    @Override
    public ResultVo delByIds(List list) {
        ResultVo resultVo = new ResultVo();
        int del = userDao.del(list);
        if (del!=0){
            resultVo.put("message","ok");
            return resultVo;
        }
        resultVo.put("message","false");
        return resultVo;
    }

    /**
     * 更新
     * @param user
     * @return
     */
    @Override
    public ResultVo update(User user) {
        ResultVo resultVo = new ResultVo();
        int del = userDao.update(user);
        if (del!=0){
            resultVo.put("message","ok");
            return resultVo;
        }
        resultVo.put("message","false");
        return resultVo;
    }
}
